from flask import render_template, current_app, session, request, jsonify, g

# from info import redis_store
from info import constants, response_code
from info.models import User, News, Category
from info.modules.index import index_blue
from info.utils.comment import user_login_data


@index_blue.route('/news_list')
def index_news_list():
    # 主页新闻列表
    # 1.接受参数：新闻分类id, 当前第几页，每页多少条数据
    cid = request.args.get('cid', 1)
    page = request.args.get('page', 1)
    per_page = request.args.get('per_page', 10)

    # 2.校验参数：参数是否齐全，参数是否都为整数
    try:
        cid = int(cid)
        page = int(page)
        per_page = int(per_page)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=response_code.RET.PARAMERR, errmsg='参数错误')

    # 3.根据参数进行分页查询

    try:
        if cid == 1:
            paginate = News.query.filter(News.status==0).order_by(News.create_time.desc()).paginate(page, per_page, False)
        else:
            paginate = News.query.filter(News.status==0, News.category_id == cid).order_by(News.create_time.desc()).paginate(page,
                                                                                                             per_page,
                                                                                                             False)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=response_code.RET.DBERR, errmsg='查询新闻数据失败')

    # 4.构造响应的数据
    # 获取当前页的数据
    news_list = paginate.items
    # 总页数
    total_page = paginate.pages
    # 当前页数
    current_page = paginate.page

    # 将模型对象列列表news_list，转成字典列列表
    news_dict_list = []
    for news in news_list:
        news_dict_list.append(news.to_basic_dict())

    # 构造新闻响应数据
    data = {'news_dict_list': news_dict_list,
            'total_page': total_page,
            'current_page': current_page
            }

    # 5.返回响应的数据
    return jsonify(errno=response_code.RET.OK, errmsg='OK', data=data)


@index_blue.route('/')
@user_login_data
def index():

    user = g.user

    # 获取新闻点击排⾏数据
    news_clicks = None

    try:
        news_clicks = News.query.order_by(News.clicks.desc()).limit(constants.CLICK_RANK_MAX_NEWS)
    except Exception as e:
        current_app.logger.error(e)

    # 获取新闻分类
    categories = None

    try:
        categories = Category.query.all()
    except Exception as e:
        current_app.logger.error(e)

    # 3构建渲染模版的数据
    context = {
        'user': user.to_dict() if user else None,
        'news_clicks': news_clicks,
        'categories': categories
    }

    # 4响应渲染后的界面
    return render_template('news/index.html', context=context)


@index_blue.route('/favicon.ico')
def favicon():
    return current_app.send_static_file('news/favicon.ico')
